﻿namespace LivePatterns
{
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Linq;
	using System.Reflection;
	using System.Reflection.Emit;

	public static partial class Build
	{
		/// <summary>
		/// Creates a snapshot of an object.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="obj">The object to take the snapshot of.</param>
		/// <returns>Returns a read-only snapshot of an object.</returns>
		/// <remarks>Snapshots are read-only.</remarks>
		/// <example>
		/// IState snapshot = Build.Snapshot&lt;IState&gt;(stream.ContinuouslyChangingState);
		/// Console.WriteLine(snapshot.Timestamp);
		/// Console.WriteLine(snapshot.Value);
		/// </example>
		public static T Snapshot<T>(T obj) where T : class
		{
			if (!typeof(T).IsInterface)
				throw new ArgumentException("Only interface types are supported.");

			// resolve type from cache, if already built
			if (_snapshotTypeCache.ContainsKey(typeof(T)))
				return Activator.CreateInstance(_snapshotTypeCache[typeof(T)], obj) as T;

			TypeBuilder typeBuilder = moduleBuilder.DefineType(String.Format("{0}_Snapshot_{1}", typeof(T).Name, Guid.NewGuid().ToString().Replace("-", "")), TypeAttributes.Class | TypeAttributes.Public);
			typeBuilder.AddInterfaceImplementation(typeof(T));

			ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(T) });
			ILGenerator cilg = constructorBuilder.GetILGenerator();
			cilg.ConstructObject();

			// implement fields
			foreach (FieldInfo fi in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance).Where(m => !m.IsSpecialName))
			{
				FieldBuilder fb = typeBuilder.DefineField(fi.Name, fi.FieldType, FieldAttributes.Public | FieldAttributes.Literal);

				// build constructor
				cilg.Emit(OpCodes.Ldarg_0);
				cilg.Emit(OpCodes.Ldarg_1);
				cilg.Emit(OpCodes.Ldfld, fi);
				cilg.Emit(OpCodes.Stfld, fb);
			}

			// implement properties
			foreach (PropertyInfo pi in typeof(T).GetAllVisibleProperties())
			{
				PropertyBuilder pb = typeBuilder.DefineProperty(pi.Name, PropertyAttributes.None, pi.PropertyType, new Type[0]);
				FieldBuilder fb = typeBuilder.DefineField(String.Format("<{0}>k__BackingField", pi.Name), pi.PropertyType, FieldAttributes.Private | FieldAttributes.SpecialName | FieldAttributes.InitOnly);

				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				// get method
				if (pi.CanRead)
				{
					MethodInfo getMethod = pi.GetGetMethod();
					methodBuilder = typeBuilder.DefineMethod(
						getMethod.Name, _methodAttributes, getMethod.ReturnType, getMethod.GetParameters().Select(p => p.ParameterType).ToArray()
					);

					ilGenerator = methodBuilder.GetILGenerator();
					ilGenerator.Emit(OpCodes.Ldarg_0);
					ilGenerator.Emit(OpCodes.Ldfld, fb);
					ilGenerator.Return();
					pb.SetGetMethod(methodBuilder);

					// build constructor
					cilg.Emit(OpCodes.Ldarg_0);
					cilg.Emit(OpCodes.Ldarg_1);
					cilg.Emit(OpCodes.Call, pi.GetGetMethod());
					cilg.Emit(OpCodes.Stfld, fb);
				}

				// set method
				if (pi.CanWrite)
				{
					MethodInfo setMethod = pi.GetSetMethod();
					methodBuilder = typeBuilder.DefineMethod(
						setMethod.Name, _methodAttributes, setMethod.ReturnType, setMethod.GetParameters().Select(p => p.ParameterType).ToArray()
					);

					ilGenerator = methodBuilder.GetILGenerator();
					ilGenerator.ThrowException(typeof(InvalidOperationException), "Cannot change a snapshot of an object.");
					pb.SetSetMethod(methodBuilder);
				}
			}

			// TODO: Create a snapshot of the elements of an enumerable
			// handle enumerable objects
			if (obj is IEnumerable)
			{
				FieldBuilder elements = typeBuilder.DefineField("elements", typeof(IEnumerable), FieldAttributes.Private);
			}

			cilg.Return();

			// implement methods
			foreach (MethodInfo mi in typeof(T).GetAllVisibleMethods())
			{
				MethodBuilder methodBuilder = typeBuilder.DefineMethod(
					mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, mi.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ILGenerator ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.ThrowException(typeof(InvalidOperationException), "Cannot change a snapshot of an object.");
			}

			// implement events
			foreach (EventInfo ei in typeof(T).GetAllVisibleEvents())
			{
				// define event
				EventBuilder eb = typeBuilder.DefineEvent(ei.Name, EventAttributes.None, ei.EventHandlerType);
				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				//
				// implement add method
				//
				MethodInfo addMethod = ei.GetAddMethod();
				methodBuilder = typeBuilder.DefineMethod(
					addMethod.Name, _methodAttributes, addMethod.ReturnType, addMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.ThrowException(typeof(InvalidOperationException), "Cannot subscribe to the events of a snapshot.");
				eb.SetAddOnMethod(methodBuilder);

				//
				// implement remove method
				//
				MethodInfo removeMethod = ei.GetRemoveMethod();
				methodBuilder = typeBuilder.DefineMethod(
					removeMethod.Name, _methodAttributes, removeMethod.ReturnType, removeMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.ThrowException(typeof(InvalidOperationException), "Cannot unsubscribe from the events of a snapshot.");
				eb.SetRemoveOnMethod(methodBuilder);
			}

			Type resultType = typeBuilder.CreateType();
			_snapshotTypeCache.Add(typeof(T), resultType);
			return Activator.CreateInstance(resultType, obj) as T;
		}

		private static readonly IDictionary<Type, Type> _snapshotTypeCache = new Dictionary<Type, Type>();
	}
}